<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>充电宝柜机模拟器</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.min.js" type="text/javascript"></script>
    <script type="text/javascript" src="http://sph.atguigu.cn/js/plugins/jquery/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/qrcodejs@1.0.0/qrcode.min.js"></script>
    <script>
        $(function () {
            // 这是$(document).ready()的简写形式
            console.log('DOM is ready!');
            var hostname = '8.138.219.48',
                port = 8083,
                clientId = '',
                timeout = 5,
                keepAlive = 100,
                cleanSession = false,
                ssl = false,
                userName = 'admin',
                password = '111',
                topic = '';
            var client = null;

            // 添加一个变量来跟踪按钮的归还状态
            var returnStatus = {};

            // 添加充电状态跟踪
            var chargingStatus = {};
            var chargingIntervals = {};

            // 添加一个变量来跟踪所有充电宝的状态
            var powerBankStatus = {};

            // 添加一个变量来存储借出的充电宝
            var borrowedPowerBanks = {};

            // 添加一个变量来存储待归还的充电宝
            var returnPowerBank = null;

            // 添加一个变量来存储柜机编号
            var cabinetNo = '';

            // 初始化借出的充电宝数据
            function initBorrowedPowerBanks () {
                var storedData = localStorage.getItem('borrowedPowerBanks');
                if (storedData) {
                    try {
                        borrowedPowerBanks = JSON.parse(storedData);
                        // 恢复所有借出的充电宝的放电状态
                        for (var powerBankNo in borrowedPowerBanks) {
                            var data = borrowedPowerBanks[powerBankNo];
                            if (data && data.slotNo && data.power !== undefined) {
                                // 重新初始化充电状态
                                chargingStatus[data.slotNo] = {
                                    power: data.power,
                                    isCharging: false,
                                    lastReportTime: Date.now()
                                };
                                // 重新开始放电
                                startDischarging(powerBankNo, data.slotNo, data.power, data.mNo);
                            }
                        }
                    } catch (e) {
                        console.error('解析存储的充电宝数据失败:', e);
                        localStorage.removeItem('borrowedPowerBanks');
                        borrowedPowerBanks = {};
                    }
                }
            }

            // 保存借出的充电宝数据
            function saveBorrowedPowerBanks () {
                try {
                    localStorage.setItem('borrowedPowerBanks', JSON.stringify(borrowedPowerBanks));
                } catch (e) {
                    console.error('保存充电宝数据失败:', e);
                }
            }

            // 创建归还充电宝显示区域
            function createReturnArea () {
                var returnArea = $('<div id="returnArea" style="margin-top: 20px; padding: 10px; border: 1px solid #ccc; border-radius: 5px;"></div>');
                var title = $('<h3 style="margin-top: 0;">已借出充电宝</h3>');
                var powerBankList = $('<div id="powerBankList"></div>');

                returnArea.append(title);
                returnArea.append(powerBankList);
                $('.container').append(returnArea);
            }

            // 更新归还充电宝显示
            function updateReturnArea () {
                var $powerBankList = $('#powerBankList');
                $powerBankList.empty();

                for (var powerBankNo in borrowedPowerBanks) {
                    var data = borrowedPowerBanks[powerBankNo];
                    var powerBankDiv = $('<div class="powerBankItem" style="margin: 5px; padding: 5px; background-color: #f5f5f5; border-radius: 3px; cursor: pointer; transition: all 0.3s;"></div>');
                    powerBankDiv.text(powerBankNo + ' (' + Math.floor(data.power) + '%)');

                    // 添加点击事件
                    powerBankDiv.click(function (e) {
                        e.stopPropagation(); // 阻止事件冒泡
                        // 移除之前选中的样式
                        $('.powerBankItem').css({
                            'border': 'none',
                            'box-shadow': 'none',
                            'transform': 'scale(1)'
                        });
                        // 添加选中样式
                        $(this).css({
                            'border': '3px solid #4CAF50',
                            'box-shadow': '0 0 10px rgba(76, 175, 80, 0.5)',
                            'transform': 'scale(1.05)'
                        });
                        // 设置当前选中的充电宝
                        returnPowerBank = $(this).text().split(' ')[0];
                    });

                    // 如果当前充电宝是选中的，添加选中样式
                    if (returnPowerBank === powerBankNo) {
                        powerBankDiv.css({
                            'border': '3px solid #4CAF50',
                            'box-shadow': '0 0 10px rgba(76, 175, 80, 0.5)',
                            'transform': 'scale(1.05)'
                        });
                    }

                    $powerBankList.append(powerBankDiv);
                }
            }

            // 添加点击事件处理，点击其他地方取消选择
            $(document).click(function (e) {
                if (!$(e.target).hasClass('powerBankItem')) {
                    // 移除所有选中样式
                    $('.powerBankItem').css({
                        'border': 'none',
                        'box-shadow': 'none',
                        'transform': 'scale(1)'
                    });
                    // 清除选中的充电宝
                    returnPowerBank = null;
                }
            });

            // 更新充电宝状态
            function updatePowerBankStatus (powerBankNo, slotNo, electricity) {
                powerBankStatus[powerBankNo] = {
                    slotNo: slotNo,
                    electricity: electricity,
                    lastUpdate: Date.now()
                };
            }

            // 计算充电速度
            function calculateChargeSpeed (currentPower) {
                // 电量越低，充电速度越快
                if (currentPower < 20) {
                    return 0.10; // 快速充电阶段
                } else if (currentPower < 50) {
                    return 0.08; // 正常充电阶段
                } else if (currentPower < 80) {
                    return 0.06; // 慢速充电阶段
                } else {
                    return 0.05; // 涓流充电阶段
                }
            }

            // 计算放电速度
            function calculateDischargeSpeed (currentPower) {
                // 电量越低，放电速度越慢
                if (currentPower < 20) {
                    return 0.02; // 低电量时放电较慢
                } else if (currentPower < 50) {
                    return 0.03; // 中等电量时放电较快
                } else if (currentPower < 80) {
                    return 0.04; // 高电量时放电最快
                } else {
                    return 0.05; // 满电时放电最快
                }
            }

            // 更新按钮显示
            function updateButtonDisplay (powerBankNo, power, slotNo) {
                var powerInt = Math.floor(power);
                var $button = $('input[type="button"][id=' + slotNo + ']');

                if ($button.length) {
                    // 如果充电宝被借出，显示为空
                    if (borrowedPowerBanks[powerBankNo]) {
                        $button.attr('value', '空');
                        $button.css("background-color", "#CCCCCC");
                        $button.css("animation", "none");
                        return;
                    }

                    // 根据电量设置不同的颜色
                    if (power < 20) {
                        $button.css("background-color", "#FF4444"); // 红色
                    } else if (power < 50) {
                        $button.css("background-color", "#FFAA00"); // 橙色
                    } else if (power < 80) {
                        $button.css("background-color", "#FFDD00"); // 黄色
                    } else {
                        $button.css("background-color", "#4CAF50"); // 绿色
                    }

                    $button.attr('value', powerBankNo + '(' + powerInt + '%)');

                    // 添加充电动画效果
                    if (chargingStatus[slotNo] && chargingStatus[slotNo].isCharging) {
                        $button.css("animation", "pulse 0.5s infinite");
                    } else {
                        $button.css("animation", "none");
                    }
                }
            }

            // 添加页面卸载事件处理
            $(window).on('beforeunload', function () {
                // 上报所有充电宝的当前电量
                for (var powerBankNo in powerBankStatus) {
                    var status = powerBankStatus[powerBankNo];
                    var currentPower = Math.floor(status.electricity);
                    var propertyMsg = {
                        mNo: generateRandomStr(),
                        cNo: cabinetNo,
                        pNo: powerBankNo,
                        sNo: status.slotNo,
                        ety: currentPower
                    };
                    send("/sys/property/post", JSON.stringify(propertyMsg));
                }
            });

            // 修改上报属性测试按钮的点击事件
            function setupReportButton () {
                $("#007").click(function () {
                    console.log("当前充电宝状态:", powerBankStatus);
                    // 遍历所有充电宝状态
                    for (var powerBankNo in powerBankStatus) {
                        var status = powerBankStatus[powerBankNo];
                        var buttonId = powerBankStatus[powerBankNo].slotNo;
                        console.log(buttonId)
                        var $button = $('#' + buttonId);

                        if ($button.length && $button.val() !== '') {
                            // 直接上报当前电量
                            var currentPower = Math.floor(status.electricity);
                            var propertyMsg = {
                                mNo: generateRandomStr(),
                                cNo: cabinetNo,
                                pNo: powerBankNo,
                                sNo: status.slotNo,
                                ety: currentPower
                            };
                            send("/sys/property/post", JSON.stringify(propertyMsg));

                            $("#content").val($("#content").val() + "上报属性: " + powerBankNo + ", 电量: " + currentPower + "%\r\n");
                            scrollToBottom();
                        }
                    }
                });
            }

            // 修改开始放电函数
            function startDischarging (powerBankNo, slotNo, initialPower, mNo) {
                var buttonId = slotNo;
                var $button = $('#' + buttonId);

                // 清除之前的充电定时器
                if (chargingIntervals[buttonId]) {
                    clearInterval(chargingIntervals[buttonId]);
                    delete chargingIntervals[buttonId];
                }

                // 设置初始电量
                var currentPower = parseFloat(initialPower);
                if (isNaN(currentPower)) {
                    // 如果电量无效，尝试从其他来源获取
                    if (powerBankStatus[powerBankNo] && powerBankStatus[powerBankNo].electricity !== undefined) {
                        currentPower = powerBankStatus[powerBankNo].electricity;
                    } else {
                        var buttonText = $button.val();
                        var powerMatch = buttonText.match(/\((\d+)%\)/);
                        if (powerMatch && powerMatch[1]) {
                            currentPower = parseFloat(powerMatch[1]);
                        } else {
                            // 如果实在获取不到电量，记录错误并返回
                            console.error('无法获取充电宝电量:', powerBankNo);
                            return;
                        }
                    }
                }

                // 根据插槽号设置不同的初始上报时间，使上报时间错开
                var initialReportTime = Date.now() + (parseInt(slotNo) * 5000); // 每个插槽错开5秒

                // 更新充电状态
                chargingStatus[buttonId] = {
                    power: currentPower,
                    isCharging: false,
                    lastReportTime: initialReportTime
                };

                // 保存到借出的充电宝列表
                borrowedPowerBanks[powerBankNo] = {
                    slotNo: slotNo,
                    power: currentPower,
                    mNo: mNo
                };
                saveBorrowedPowerBanks();
                updateReturnArea();

                // 更新按钮显示
                updateButtonDisplay(powerBankNo, currentPower, slotNo);

                // 动态放电过程
                chargingIntervals[buttonId] = setInterval(function () {
                    if (chargingStatus[buttonId] && !chargingStatus[buttonId].isCharging) {
                        // 根据当前电量计算放电速度
                        var dischargeSpeed = calculateDischargeSpeed(currentPower);
                        currentPower = Math.max(0, currentPower - dischargeSpeed);
                        chargingStatus[buttonId].power = currentPower;

                        // 更新借出的充电宝数据
                        if (borrowedPowerBanks[powerBankNo]) {
                            borrowedPowerBanks[powerBankNo].power = currentPower;
                            saveBorrowedPowerBanks();
                            updateReturnArea();
                        }

                        // 更新按钮显示
                        updateButtonDisplay(powerBankNo, currentPower, slotNo);

                        // 更新充电宝状态
                        updatePowerBankStatus(powerBankNo, slotNo, currentPower);

                        // 如果电量达到0%，停止放电
                        if (currentPower <= 0) {
                            clearInterval(chargingIntervals[buttonId]);
                            delete chargingIntervals[buttonId];
                            chargingStatus[buttonId].isCharging = false;
                            $("#content").val($("#content").val() + "放电完成: " + powerBankNo + "\r\n");
                            scrollToBottom();
                        }
                    }
                }, 1000); // 每秒更新一次
            }

            // 修改按钮点击事件
            function setupButtonClick ($button, powerBankNo, slotNo) {
                $button.off('click');
                $button.on('click', function () {
                    // 如果按钮显示为空，说明可以归还充电宝
                    if ($button.val() === '空') {
                        if (returnPowerBank) {
                            // 如果有选中的待归还充电宝，执行归还操作
                            var borrowedData = borrowedPowerBanks[returnPowerBank];
                            if (!borrowedData) {
                                alert("充电宝数据不存在");
                                return;
                            }

                            var currentPower = 0;
                            // 尝试从多个来源获取电量
                            if (borrowedData.power !== undefined) {
                                currentPower = borrowedData.power;
                            } else if (powerBankStatus[returnPowerBank] && powerBankStatus[returnPowerBank].electricity !== undefined) {
                                currentPower = powerBankStatus[returnPowerBank].electricity;
                            } else {
                                // 如果都获取不到，从按钮文本中提取电量
                                var buttonText = $button.val();
                                var powerMatch = buttonText.match(/\((\d+)%\)/);
                                if (powerMatch && powerMatch[1]) {
                                    currentPower = parseFloat(powerMatch[1]);
                                } else {
                                    alert("无法获取充电宝电量");
                                    return;
                                }
                            }

                            // 清除旧位置的充电状态
                            if (borrowedData.slotNo) {
                                if (chargingIntervals[borrowedData.slotNo]) {
                                    clearInterval(chargingIntervals[borrowedData.slotNo]);
                                    delete chargingIntervals[borrowedData.slotNo];
                                }
                                delete chargingStatus[borrowedData.slotNo];
                            }

                            // 初始化新位置的充电状态
                            chargingStatus[slotNo] = {
                                power: currentPower,
                                isCharging: true,
                                lastReportTime: Date.now() + (parseInt(slotNo) * 5000)
                            };

                            // 开始充电
                            startCharging(returnPowerBank, slotNo, currentPower);

                            var mNo = generateRandomStr();
                            // 确保使用最新的柜机编号
                            var connectedMsg = {
                                mNo: mNo,
                                cNo: cabinetNo,
                                pNo: returnPowerBank,
                                sNo: slotNo,
                                ety: Math.floor(currentPower)
                            };
                            send("/sys/powerBank/connected", JSON.stringify(connectedMsg));

                            // 从借出的充电宝列表中移除
                            delete borrowedPowerBanks[returnPowerBank];
                            saveBorrowedPowerBanks();

                            // 重置选中的充电宝
                            returnPowerBank = null;

                            // 更新显示
                            updateReturnArea();
                        } else {
                            // 如果没有选中的待归还充电宝，提示用户先选择
                            alert("请先选择要归还的充电宝");
                        }
                    }
                });
            }

            // 修改开始充电函数
            function startCharging (powerBankNo, slotNo, initialPower) {
                var buttonId = slotNo;
                var $button = $('input[type="button"][id="' + buttonId + '"]');

                // 清除之前的充电定时器
                if (chargingIntervals[buttonId]) {
                    clearInterval(chargingIntervals[buttonId]);
                    delete chargingIntervals[buttonId];
                }

                // 设置初始电量
                var currentPower = parseFloat(initialPower);
                if (isNaN(currentPower)) {
                    // 如果电量无效，尝试从其他来源获取
                    if (powerBankStatus[powerBankNo] && powerBankStatus[powerBankNo].electricity !== undefined) {
                        currentPower = powerBankStatus[powerBankNo].electricity;
                    } else {
                        var buttonText = $button.val();
                        var powerMatch = buttonText.match(/\((\d+)%\)/);
                        if (powerMatch && powerMatch[1]) {
                            currentPower = parseFloat(powerMatch[1]);
                        } else {
                            // 如果实在获取不到电量，记录错误并返回
                            console.error('无法获取充电宝电量:', powerBankNo);
                            return;
                        }
                    }
                }

                // 根据插槽号设置不同的初始上报时间，使上报时间错开
                var initialReportTime = Date.now() + (parseInt(slotNo) * 5000); // 每个插槽错开5秒

                // 更新充电状态
                chargingStatus[buttonId] = {
                    power: currentPower,
                    isCharging: true,
                    lastReportTime: initialReportTime
                };

                // 更新按钮显示
                updateButtonDisplay(powerBankNo, currentPower, slotNo);

                // 动态充电过程
                chargingIntervals[buttonId] = setInterval(function () {
                    if (chargingStatus[buttonId] && chargingStatus[buttonId].isCharging) {
                        // 根据当前电量计算充电速度
                        var chargeSpeed = calculateChargeSpeed(currentPower);
                        currentPower = Math.min(100, currentPower + chargeSpeed);
                        chargingStatus[buttonId].power = currentPower;

                        // 更新按钮显示
                        updateButtonDisplay(powerBankNo, currentPower, slotNo);

                        // 更新充电宝状态
                        updatePowerBankStatus(powerBankNo, slotNo, currentPower);

                        // 如果电量达到100%，停止充电
                        if (currentPower >= 100) {
                            clearInterval(chargingIntervals[buttonId]);
                            delete chargingIntervals[buttonId];
                            chargingStatus[buttonId].isCharging = false;
                            $button.css("animation", "none");
                            $("#content").val($("#content").val() + "充电完成: " + powerBankNo + "\r\n");
                            scrollToBottom();
                        }
                    }
                }, 1000); // 每秒更新一次
            }

            function onMessageArrived (message) {
                console.log("收到消息:" + message.payloadString);
                $("#content").val($("#content").val() + "\r\n")
                $("#content").val($("#content").val() + "收到消息Topic：" + message.destinationName + "\r\n")
                $("#content").val($("#content").val() + "收到消息：" + message.payloadString + "\r\n")
                scrollToBottom();

                // 解析消息内容
                var msgData;
                try {
                    msgData = JSON.parse(message.payloadString);
                } catch (e) {
                    // 如果不是JSON格式，尝试使用竖线分隔格式
                    var msgParts = message.payloadString.split('|');
                    msgData = {};
                    msgParts.forEach(function (part) {
                        var keyValue = part.split('=');
                        if (keyValue.length === 2) {
                            msgData[keyValue[0]] = keyValue[1];
                        }
                    });
                }

                // 获取消息中的各个字段
                var mNo = msgData.mNo;
                var powerBankNo = msgData.pNo;
                var slotNo = msgData.sNo;
                var cabinetNo = msgData.cNo;
                var userId = msgData.uId || "1"; // 默认用户ID为1

                // 如果是扫描提交消息，立即发送开锁消息
                if (message.destinationName.startsWith("/sys/scan/submit/")) {
                    var unlockMsg = {
                        mNo: mNo,
                        sNo: slotNo,
                        uId: parseInt(userId),
                        pNo: powerBankNo,
                        cNo: cabinetNo
                    };
                    send("/sys/powerBank/unlock", JSON.stringify(unlockMsg));
                }

                // 找到对应的按钮
                var buttonId = slotNo;
                var $button = $('#' + buttonId);

                if ($button.length) {
                    // 如果正在充电，停止充电
                    if (chargingIntervals[buttonId]) {
                        clearInterval(chargingIntervals[buttonId]);
                        chargingStatus[buttonId].isCharging = false;
                        $("#content").val($("#content").val() + "停止充电: " + powerBankNo + "\r\n");
                    }

                    // 打印chargingStatus数据
                    $("#content").val($("#content").val() + "当前充电状态数据：\r\n");
                    for (var key in chargingStatus) {
                        if (chargingStatus[key]) {
                            $("#content").val($("#content").val() + "插槽" + key + ": " +
                                "电量=" + chargingStatus[key].power +
                                ", 充电状态=" + (chargingStatus[key].isCharging ? "充电中" : "未充电") +
                                ", 最后上报时间=" + new Date(chargingStatus[key].lastReportTime).toLocaleString() + "\r\n");
                        }
                    }
                    scrollToBottom();

                    // 获取当前电量
                    var currentPower = 0;
                    if (chargingStatus[buttonId] && chargingStatus[buttonId].power !== undefined) {
                        currentPower = chargingStatus[buttonId].power;
                    } else if (powerBankStatus[powerBankNo] && powerBankStatus[powerBankNo].electricity !== undefined) {
                        currentPower = powerBankStatus[powerBankNo].electricity;
                    } else {
                        // 如果都获取不到，从按钮文本中提取电量
                        var buttonText = $button.val();
                        var powerMatch = buttonText.match(/\((\d+)%\)/);
                        if (powerMatch && powerMatch[1]) {
                            currentPower = parseFloat(powerMatch[1]);
                        }
                    }

                    // 开始放电（模拟借出）
                    startDischarging(powerBankNo, slotNo, currentPower, mNo);
                }
            }

            function send (topic, message) {
                if (!client || !client.isConnected()) {
                    $("#content").val($("#content").val() + "MQTT未连接，无法发送消息\r\n");
                    scrollToBottom();
                    return;
                }

                msg = new Paho.MQTT.Message(message);
                msg.destinationName = topic;
                client.send(msg);

                $("#content").val($("#content").val() + "\r\n")
                $("#content").val($("#content").val() + "发布消息Topic：" + topic + "\r\n")
                $("#content").val($("#content").val() + "发布消息：" + message + "\r\n")
                scrollToBottom();
            }

            // 添加自动滚动到底部的函数
            function scrollToBottom () {
                var textarea = document.getElementById('content');
                textarea.scrollTop = textarea.scrollHeight;
            }

            function generateRandomStr () {
                const min = 10000000; // 10位数的最小值
                const max = 99999999; // 10位数的最大值
                const randomNum = Math.floor(Math.random() * (max - min + 1)) + min;
                return 'mq' + randomNum.toString();
            }

            // 连接成功处理函数
            function onConnect () {
                console.log("MQTT连接成功");
                $("#content").val($("#content").val() + "\r\nMQTT连接成功\r\n");
                scrollToBottom();

                // 订阅主题
                client.subscribe(topic);
                $("#content").val($("#content").val() + "已订阅主题: " + topic + "\r\n");
                scrollToBottom();

                // 显示连接信息
                $("#content").val($("#content").val() + "\r\n连接信息：\r\n");
                $("#content").val($("#content").val() + "主机: " + hostname + "\r\n");
                $("#content").val($("#content").val() + "端口: " + port + "\r\n");
                $("#content").val($("#content").val() + "客户端ID: " + clientId + "\r\n");
                $("#content").val($("#content").val() + "主题: " + topic + "\r\n");
                scrollToBottom();

                $("#cabinetIdInput button").prop('disabled', false);
            }

            // 处理机柜编号输入
            $("#cabinetIdForm").submit(function (e) {
                e.preventDefault();
                var cabinetId = $("#cabinetId").val();
                if (cabinetId) {
                    // 显示加载效果
                    $("#cabinetButtons").html('<div style="text-align: center; margin-top: 20px;">加载中...</div>');
                    $("#cabinetIdInput button").prop('disabled', true);

                    // 清除所有充电宝状态和充电定时器
                    for (var buttonId in chargingIntervals) {
                        if (chargingIntervals[buttonId]) {
                            clearInterval(chargingIntervals[buttonId]);
                            delete chargingIntervals[buttonId];
                        }
                    }

                    // 上报所有充电宝的当前电量
                    for (var powerBankNo in powerBankStatus) {
                        var status = powerBankStatus[powerBankNo];
                        if (status && status.electricity !== undefined) {
                            var currentPower = Math.floor(status.electricity);
                            var propertyMsg = {
                                mNo: generateRandomStr(),
                                cNo: cabinetNo,
                                pNo: powerBankNo,
                                sNo: status.slotNo,
                                ety: currentPower
                            };
                            send("/sys/property/post", JSON.stringify(propertyMsg));
                            $("#content").val($("#content").val() + "切换柜机，上报充电宝状态: " + powerBankNo + ", 电量: " + currentPower + "%\r\n");
                        }
                    }
                    scrollToBottom();

                    // 重置所有状态变量
                    chargingIntervals = {};
                    chargingStatus = {};
                    returnStatus = {};
                    powerBankStatus = {};

                    // 如果MQTT客户端存在，断开连接
                    if (client) {
                        try {
                            if (client.isConnected()) {
                                client.disconnect();
                            }
                            client = null;
                        } catch (e) {
                            console.error('断开MQTT连接失败:', e);
                        }
                    }

                    // 延迟一下再获取新柜机信息，确保连接完全断开
                    setTimeout(function () {
                        getCabinetInfo(cabinetId);
                    }, 1000);
                } else {
                    alert("请输入机柜编号");
                }
            });

            // 获取柜机信息
            function getCabinetInfo (cabinetId) {
                // 从本地获取柜机信息
                $.ajax({
                    url: 'http://127.0.0.1:18080/device/cabinet/ByCabinetNo/' + cabinetId,
                    type: 'GET',
                    success: function (response) {
                        console.log('柜机信息:', response);
                        $("#content").val($("#content").val() + "获取柜机信息成功\r\n");

                        if (response.code === 200 && response.data) {
                            // 清空现有的按钮
                            $("#cabinetButtons").empty();

                            // 获取柜机信息
                            var cabinet = response.data;
                            var slotCount = cabinet.totalSlots || 8; // 使用totalSlots作为插槽数量

                            // 保存柜机编号
                            cabinetNo = cabinet.cabinetNo;
                            // 获取柜机对应的充电宝信息
                            $.ajax({
                                url: 'http://127.0.0.1:18080/device/powerBank/getPowerBankByCabinetId/' + cabinet.id,
                                type: 'GET',
                                success: function (powerBankResponse) {
                                    $("#content").val($("#content").val() + "获取充电宝信息成功\r\n");

                                    if (powerBankResponse.code === 200 && powerBankResponse.data) {
                                        // 将对象转换为数组
                                        var powerBanks = [];
                                        for (var key in powerBankResponse.data) {
                                            if (powerBankResponse.data.hasOwnProperty(key)) {
                                                var powerBank = powerBankResponse.data[key];
                                                // 从powerBankNo中提取插槽号
                                                var slotNo = parseInt(key);
                                                powerBank.slotNo = slotNo;
                                                powerBanks.push(powerBank);
                                            }
                                        }

                                        // 创建按钮表格
                                        var table = $('<table></table>');
                                        var row = $('<tr></tr>');

                                        // 动态创建按钮
                                        for (var i = 1; i <= slotCount; i++) {
                                            var slotNo = i.toString();
                                            var powerBankNo = '';

                                            // 查找对应插槽的充电宝
                                            for (var key in powerBankResponse.data) {
                                                if (powerBankResponse.data[key] && powerBankResponse.data[key].slotNo === i) {
                                                    powerBankNo = powerBankResponse.data[key].powerBankNo;
                                                    break;
                                                }
                                            }

                                            // 每4个按钮一行
                                            if (i > 1 && (i - 1) % 4 === 0) {
                                                table.append(row);
                                                row = $('<tr></tr>');
                                            }

                                            var td = $('<td></td>');
                                            var button = createButton(slotNo, powerBankNo);
                                            td.append(button);
                                            row.append(td);
                                        }

                                        // 添加最后一行（即使不满4个按钮）
                                        if (row.children().length > 0) {
                                            table.append(row);
                                        }

                                        // 添加上报属性按钮和柜机图片
                                        var lastRow = $('<tr></tr>');
                                        var reportTd = $('<td></td>');
                                        var reportButton = $('<input type="button" id="007" value="上报属性测试" style="background-color:#333000" />');
                                        reportTd.append(reportButton);
                                        lastRow.append(reportTd);

                                        var imgTd = $('<td></td>');
                                        // 创建二维码容器
                                        var qrCodeDiv = $('<div id="qrCode" style="text-align: center;"></div>');
                                        imgTd.append(qrCodeDiv);
                                        lastRow.append(imgTd);

                                        table.append(lastRow);

                                        // 将表格添加到容器中
                                        $("#cabinetButtons").append(table);

                                        // 显示文本区域
                                        $("#content").show();

                                        // 设置上报属性按钮的点击事件
                                        setupReportButton();

                                        // 更新所有充电宝按钮的状态
                                        if (powerBankResponse.data) {
                                            for (var key in powerBankResponse.data) {
                                                var powerBank = powerBankResponse.data[key];
                                                if (powerBank) {
                                                    var $button = $('input[type="button"][id=' + powerBank.slotNo + ']');
                                                    if ($button.length) {
                                                        // 更新按钮显示
                                                        updateButtonDisplay(powerBank.powerBankNo, powerBank.electricity, powerBank.slotNo);
                                                        // 更新充电宝状态
                                                        updatePowerBankStatus(powerBank.powerBankNo, powerBank.slotNo, powerBank.electricity);

                                                        // 如果电量低于100%且未归还，开始充电
                                                        if (powerBank.electricity < 100 && !returnStatus[powerBank.powerBankNo]) {
                                                            startCharging(powerBank.powerBankNo, powerBank.slotNo, powerBank.electricity);
                                                        }
                                                    }
                                                }
                                            }
                                        }

                                        // 在DOM完全加载后生成二维码
                                        setTimeout(function () {
                                            if (document.getElementById("qrCode")) {
                                                var qrcode = new QRCode(document.getElementById("qrCode"), {
                                                    text: cabinet.cabinetNo,
                                                    width: 80,
                                                    height: 80,
                                                    colorDark: "#000000",
                                                    colorLight: "#ffffff",
                                                    correctLevel: QRCode.CorrectLevel.H
                                                });
                                            }
                                        }, 100);

                                        // 更新MQTT客户端ID和连接
                                        clientId = cabinet.cabinetNo || 'gj001';
                                        topic = '/sys/scan/submit/' + clientId;

                                        // 确保之前的连接已经完全断开
                                        if (client) {
                                            try {
                                                if (client.isConnected()) {
                                                    client.disconnect();
                                                }
                                                client = null;
                                            } catch (e) {
                                                console.error('断开MQTT连接失败:', e);
                                            }
                                        }

                                        // 创建MQTT客户端
                                        client = new Paho.MQTT.Client(hostname, port, clientId);

                                        // 设置连接选项
                                        var options = {
                                            invocationContext: {
                                                host: hostname,
                                                port: port,
                                                path: client.path,
                                                clientId: clientId
                                            },
                                            timeout: timeout,
                                            keepAliveInterval: keepAlive,
                                            cleanSession: cleanSession,
                                            useSSL: ssl,
                                            userName: userName,
                                            password: password,
                                            onSuccess: onConnect,
                                            onFailure: function (e) {
                                                console.log(e);
                                                $("#content").val($("#content").val() + "MQTT连接失败: " + e.errorMessage + "\r\n");
                                                scrollToBottom();
                                            }
                                        };

                                        // 连接MQTT服务器
                                        client.connect(options);

                                        // 设置消息到达处理函数
                                        client.onMessageArrived = onMessageArrived;

                                        // 设置连接断开处理函数
                                        client.onConnectionLost = function (responseObject) {
                                            if (responseObject.errorCode !== 0) {
                                                console.log("onConnectionLost:" + responseObject.errorMessage);
                                                $("#content").val($("#content").val() + "\r\n<span style='color: red;'>MQTT连接已断开: " + responseObject.errorMessage + "</span>\r\n");
                                                $("#content").val($("#content").val() + "<span style='color: red;'>断开时间: " + new Date().toLocaleString() + "</span>\r\n");
                                                scrollToBottom();

                                                // 在充电柜区域显示服务断开提示
                                                var disconnectMsg = $('<div style="text-align: center; color: red; font-size: 1.2em; margin: 20px 0; font-weight: bold;">服务已断开</div>');
                                                $("#cabinetButtons").empty().append(disconnectMsg);
                                            }
                                        };

                                        $("#content").val($("#content").val() + "柜机编号: " + cabinet.cabinetNo + ", 插槽数量: " + slotCount + "\r\n");
                                        $("#content").val($("#content").val() + "柜机名称: " + cabinet.name + ", 描述: " + cabinet.description + "\r\n");
                                        $("#content").val($("#content").val() + "可用插槽: " + cabinet.availableNum + ", 已用插槽: " + cabinet.usedSlots + "\r\n");
                                    } else {
                                        $("#content").val($("#content").val() + "获取充电宝信息失败: " + powerBankResponse.msg + "\r\n");
                                    }
                                },
                                error: function (xhr, status, error) {
                                    console.error('获取充电宝信息失败:', error);
                                    $("#content").val($("#content").val() + "获取充电宝信息失败: " + error + "\r\n");
                                }
                            });
                        } else {
                            $("#content").val($("#content").val() + "获取柜机信息失败: " + response.msg + "\r\n");
                        }
                    },
                    error: function (xhr, status, error) {
                        console.error('获取柜机信息失败:', error);
                        $("#content").val($("#content").val() + "获取柜机信息失败: " + error + "\r\n");
                    }
                });
            }

            // 在创建按钮时调用setupButtonClick
            function createButton (slotNo, powerBankNo) {
                var buttonId = slotNo;
                var $button = $('<input type="button" id="' + buttonId + '" value="空" style="background-color: #CCCCCC;" />');

                setupButtonClick($button, powerBankNo, slotNo);

                return $button;
            }

            // 在页面加载时初始化
            $(function () {
                createReturnArea();
                initBorrowedPowerBanks();

                // 添加初始提示内容
                var initialContent = "欢迎使用充电宝柜机模拟器\r\n";
                initialContent += "请按照以下步骤操作：\r\n";
                initialContent += "1. 在输入框中输入柜机编号（例如：gj001）\r\n";
                initialContent += "2. 点击确定按钮连接柜机\r\n";
                initialContent += "3. 连接成功后，您将看到柜机中的充电宝状态\r\n";
                initialContent += "4. 可以通过扫描二维码来借充电宝，全自动归还充电宝\r\n";
                initialContent += "5. 所有操作记录都会显示在下方的消息区域\r\n\r\n";

                $("#content").val(initialContent).show();
                scrollToBottom();

                // 在充电柜区域添加初始提示
                var initialCabinetMsg = $('<div style="text-align: center; color: #666; font-size: 1.1em; margin: 40px 0; line-height: 1.6;">');
                initialCabinetMsg.append('<p style="margin-bottom: 15px;">请先输入柜机编号</p>');
                initialCabinetMsg.append('<p style="color: #999; font-size: 0.9em;">输入后点击确定按钮连接柜机</p>');
                initialCabinetMsg.append('</div>');
                $("#cabinetButtons").append(initialCabinetMsg);
            });
        });
    </script>
</head>

<body>
    <div class="container">
        <div class="header">
            <h1>充电宝柜机模拟器</h1>
        </div>
        <div id="cabinetIdInput" class="input-section">
            <form id="cabinetIdForm">
                <label for="cabinetId">请输入机柜编号：</label>
                <input type="text" id="cabinetId" placeholder="例如：gj001" />
                <button type="submit">确定</button>
            </form>
        </div>
        <div id="cabinetButtons" class="cabinet-section">
            <!-- 动态创建的按钮将在这里显示 -->
        </div>
        <div class="content-section">
            <textarea id="content" rows="15" cols="100" style="width: 100%; display: none;"></textarea>
        </div>
    </div>
</body>

<style>
    /* 全局样式 */
    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
        font-family: 'Microsoft YaHei', sans-serif;
    }

    body {
        background-color: #f5f5f5;
        color: #333;
    }

    /* 容器样式 */
    .container {
        max-width: 800px;
        margin: 0 auto;
        padding: 15px;
        display: flex;
        flex-direction: column;
        gap: 15px;
    }

    /* 头部样式 */
    .header {
        text-align: center;
        padding: 10px 0;
    }

    .header h1 {
        color: #2c3e50;
        font-size: 1.8em;
        margin-bottom: 5px;
    }

    /* 输入区域样式 */
    .input-section {
        background-color: white;
        padding: 15px;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }

    #cabinetIdInput form {
        display: flex;
        align-items: center;
        gap: 10px;
    }

    #cabinetIdInput label {
        font-size: 1em;
        color: #2c3e50;
    }

    #cabinetIdInput input {
        padding: 8px 12px;
        border: 1px solid #ddd;
        border-radius: 4px;
        font-size: 0.9em;
        flex: 1;
        transition: border-color 0.3s;
    }

    #cabinetIdInput input:focus {
        border-color: #4CAF50;
        outline: none;
    }

    #cabinetIdInput button {
        padding: 8px 15px;
        background-color: #4CAF50;
        color: white;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        font-size: 0.9em;
        transition: background-color 0.3s;
    }

    #cabinetIdInput button:hover {
        background-color: #45a049;
    }

    /* 柜机区域样式 */
    .cabinet-section {
        background-color: white;
        padding: 15px;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }

    table {
        margin: 0 auto;
        table-layout: fixed;
        width: 100%;
        max-width: 600px;
        border-collapse: separate;
        border-spacing: 8px;
    }

    td {
        width: 25%;
        height: 80px;
        text-align: center;
    }

    input[type="button"] {
        width: 100%;
        height: 60px;
        background-color: #4CAF50;
        color: white;
        border: none;
        border-radius: 6px;
        cursor: pointer;
        font-size: 1em;
        transition: all 0.3s;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }

    input[type="button"]:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
    }

    input[type="button"][value="空"] {
        background-color: #CCCCCC;
    }

    /* 内容区域样式 */
    .content-section {
        background-color: white;
        padding: 20px;
        border-radius: 10px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    }

    /* 充电宝项目样式 */
    .powerBankItem {
        margin: 8px;
        padding: 10px;
        background-color: #f8f9fa;
        border-radius: 6px;
        cursor: pointer;
        transition: all 0.3s;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
    }

    .powerBankItem:hover {
        background-color: #e9ecef;
        transform: translateY(-2px);
    }

    /* 动画效果 */
    @keyframes pulse {
        0% {
            transform: scale(1);
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        }

        50% {
            transform: scale(1.05);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
        }

        100% {
            transform: scale(1);
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        }
    }

    /* 响应式设计 */
    @media (max-width: 768px) {
        .container {
            padding: 10px;
        }

        .header h1 {
            font-size: 1.5em;
        }

        table {
            border-spacing: 4px;
        }

        td {
            height: 60px;
        }

        input[type="button"] {
            height: 50px;
            font-size: 0.9em;
        }
    }
</style>

</html>